<?php

namespace Api\Controller;

use Think\Controller;


class WeChatController extends PublicController
{

    private $appid = 'wx885e5bd4813c58c9';                 //微信公众号APPID
    private $appsecret = '7529c92260da2e583cca2355bc28499a';             //密匙
    private $url = 'http://jewelry.bndvip.com/index.php?m=Api&c=WeChat&a=login';

    /**
     * 微信回调
     */

    /**
     * 微信登陆开始
     */
    public function start()
    {
        $pid = I('get.uid');
        $_SESSION['pid'] = $pid;
        $good_id = I('get.goods_id');
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' . $this->appid . '&redirect_uri=' . urlencode($this->url . "&goods_id=$good_id") . '&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirect';
        header('location:' . $url);
    }

    /**
     * 登录
     */
    public function login()
    {
        $code = $_GET['code'];
        $access_token = $this->getUserAccessToken($code);
        $UserInfo = $this->getUserInfo($access_token);
        $openid = $UserInfo['openid'];
        $data['openid'] = $openid;
        $data['nickname'] = match_chinese($UserInfo['nickname']);
        $data['headimgurl'] = $UserInfo['headimgurl'];
        $data['sex'] = $UserInfo['sex'];
        $data['addtime'] = time();
        $data['pid'] = $_SESSION['pid'];

        $user_info = M('user')->where("openid='$openid'")->find();
        $goods_id = I('request.goods_id');
        if ($user_info) {

            //已经登陆过
            $user_id = $user_info['user_id'];

            $data['union_id'] = $user_info['unionid'];
            $_SESSION['user_id'] = $user_id;
            M('user')->where("user_id='$user_id'")->save($data);
            if (empty($goods_id)) {
                header("location:http://hill.bndvip.com/html/pages/home/home.wxml");
            } else {
                header("location:http://hill.bndvip.com/html/pages/home/home.wxml");
            }

        } else {

            //未登陆过
            $randNum = $this->getRandString(6);
            $data['key'] = randstr(32);
            //  $data['user_id'] = date('YmdHis') . $randNum;
            // $data['shop_integral'] = 100;
            $data['union_id'] = $user_info['unionid'];
            $_SESSION['user_id'] = $data['user_id'];


            if ($data) {
                $result = M('user')->add($data);

            }

            if ($result != false) {
                M()->commit();
                if (empty($goods_id)) {
                    header("location:http://hill.bndvip.com/html/pages/home/home.wxml");
                } else {
                    header("location:http://hill.bndvip.com/html/pages/home/home.wxml");
                }

            } else {
                M()->rollback();
                $this->ajaxreturn(array('state' => -1, 'message' => "插入数据失败"), 'json');
            }

        }
    }

    /**
     * @param $jscode
     * @return mixed小程序微信授权
     */
    public function getOpenid()
    {
        $jscode=$_REQUEST['js_code'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$this->appid&secret==$this->appsecret&js_code=" . $jscode . "&grant_type=authorization_code";
        $res = file_get_contents($url);
        if(empty($res)){
            $this->ajaxreturn(array('state'=>0),'json');
        }else{
            $this->ajaxreturn(array('state'=>1,'data'=>json_decode($res)),'json');
        }
     }

    /**
     * 获取授权token
     * @param $code
     * @return bool|string
     */
    private function getUserAccessToken($code)
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$this->appid&secret=$this->appsecret&code=$code&grant_type=authorization_code";
        $res = file_get_contents($url);
        return json_decode($res);
    }

    /**
     * 获取用户信息
     * @param $accessToken
     * @return mixed
     */
    private function getUserInfo($accessToken)
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=$accessToken->access_token&openid=$accessToken->openid&lang=zh_CN";
        $UserInfo = file_get_contents($url);
        return json_decode($UserInfo, true);
    }

    /**
     * 此AccessToken   与 getUserAccessToken不一样
     * 获得AccessToken
     * @return mixed
     */
    private function getAccessToken()
    {
        // 获取缓存
        $access = S('access_token');

        // 缓存不存在-重新创建
        if (empty($access)) {

            // 获取 access token
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this -> appid}&secret={$this->appsecret}";
            $accessToken = file_get_contents($url);
            $accessToken = json_decode($accessToken);

            // 保存至缓存
            $access = $accessToken->access_token;
            S('access_token', $access, 7200);
        }
        return $access;
    }

    /**
     * 获取JS证明
     * @param $accessToken
     * @return mixed
     */
    private function _getJsapiTicket($accessToken)
    {

        // 获取缓存
        $ticket = S('jsapi_ticket');
        // 缓存不存在-重新创建
        if (empty($ticket)) {
            // 获取js_ticket
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" . $accessToken . "&type=jsapi";
            $jsTicket = file_get_contents($url);

            $jsTicket = json_decode($jsTicket);

            // 保存至缓存
            $ticket = $jsTicket->ticket;
            S('jsapi_ticket', $ticket, 7200);
        }
        return $ticket;
    }

    /**
     * 获取JS-SDK调用权限
     */
    public function shareAPi()
    {
        $url = I('post.url');
        $url = htmlspecialchars_decode($url);
        // 获取accesstoken
        $accessToken = $this->getAccessToken();

        // 获取jsapi_ticket
        $jsapiTicket = $this->_getJsapiTicket($accessToken);

//        $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
//        $url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

        $timestamp = time();
        $nonceStr = $this->createNonceStr();
        // -------- 生成签名 --------

        $wxConf = array(
            'jsapi_ticket' => $jsapiTicket,
            'noncestr' => "$nonceStr",
            'timestamp' => $timestamp,
            'url' => "$url"    //这个就是你要自定义分享页面的Url啦  );
        );
//        $this->ajaxreturn($url);
        $string1 = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        // 计算签名
        $wxConf['string1'] = $string1;
        $wxConf['signature'] = sha1($string1);

        $this->ajaxreturn(array('data' => $wxConf), 'json');
    }

    /**
     * @param int $length
     * @return string随机字符串
     */
    private function createNonceStr($length = 16)
    {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * @param $openid
     * 推送的数据
     */
    public function push($openid, $type)
    {
        $data = [
            'touser' => $openid,
            'template_id' => 'Prn-4BYHki5A_ExQ3mqVatvB23an8rtFbt4zL5zBCZM',
            'url' => 'http://jewelry.bndvip.com/html/personal.html',
            'topcolor' => "#FF0000",
            'data' => array(
                'keyword1' => array('value' => '恭喜您已经成为了' . $type, "color" => "#173177"),
                'keyword2' => array('value' => '暂无', "color" => "#173177"),
                'keyword3' => array('value' => date("Y-m-d H:i:s", time()), "color" => "#173177"),
            ),
        ];
        $result = $this->curl_post_send_information($this->getAccessToken(), json_encode($data));
    }

    /**
     * @param $openid
     * 首次关注的时候送100购物积分推送
     */
    public function pushIntegral($openid)
    {
        $data = [
            'touser' => $openid,
            'template_id' => 'ufa85Jop41Tye6_6pcVEBZC8DC17XxvEyO-PA96yjq8',
            'url' => 'http://jewelry.bndvip.com/html/index.html',
            'topcolor' => "#FF0000",
            'data' => array(
                'keyword1' => array('value' => date("Y-m-d H:i:s", time()), "color" => "#173177"),
                'keyword2' => array('value' => '微信首次关注', "color" => "#173177"),
                'keyword3' => array('value' => '恭喜您已经获得100购物积分', "color" => "#173177"),
            ),
        ];
        $result = $this->curl_post_send_information($this->getAccessToken(), json_encode($data));
    }


    /**
     * @param $token
     * @param $vars
     * @param int $second
     * @param array $aHeader
     * @return int|mixed推送的主体
     */
    public function curl_post_send_information($token, $vars, $second = 120, $aHeader = array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        curl_setopt($ch, CURLOPT_URL, 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $token);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            return $error;
        }
    }


}
